package com.tsingeye.viid.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tsingeye.common.config.MinioConfig;
import com.tsingeye.common.utils.ImageUtils;
import com.tsingeye.common.utils.SnowflakeGenerateIdUtil;
import com.tsingeye.common.utils.StringUtils;
import com.tsingeye.common.utils.file.FileUploadUtils;
import com.tsingeye.common.utils.file.MinioUtil;
import com.tsingeye.viid.domain.*;
import com.tsingeye.viid.service.ViidFaceService;
import com.tsingeye.viid.service.ViidMotorVehicleService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Api(tags = "通知")
@RestController
@Slf4j
public class ViidNotificationController {

    @Autowired
    private MinioConfig minioConfig;

    @Autowired
    private MinioUtil minioUtil;

    @Autowired
    private ViidFaceService viidFaceService;

    @Autowired
    private ViidMotorVehicleService viidMotorVehicleService;

    /**
     * 订阅通知
     */
    @RequestMapping(value = "/VIID/SubscribeNotifications", method = RequestMethod.POST)
    public String subscribeNotifications(@RequestBody String notifications) {
        JSONObject result = new JSONObject();
        JSONObject responseStatusListObject = new JSONObject();
        JSONArray responseStatusObject = new JSONArray();
        //log.info("通知数据：{}", subscribeNotificationListObject);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        // 获取请求的object
        JSONObject jp = JSONObject.parseObject(notifications);
        // 从请求的Object中获取SubscribeNotificationListObject
        JSONObject subscribeNotificationListObject = (JSONObject) jp.get("SubscribeNotificationListObject");
        // 从subscribeNotificationListObject中获取"SubscribeNotificationObject"
        JSONArray subscribeNotificationObject = subscribeNotificationListObject.getJSONArray("SubscribeNotificationObject");
        for (Object notifyObject : subscribeNotificationObject) {
            JSONObject notificationObj = (JSONObject) notifyObject;
            String notifyId = notificationObj.getString("NotificationID");
            if (notificationObj.containsKey("FaceObjectList")) {
                List<ViidFaceRequest> insertFaceList = new ArrayList<>();
                List<SubImageInfo> insertImageList = new ArrayList<>();
                // 从请求的Object中获取FaceListObject
                JSONObject faceListObject = notificationObj.getJSONObject("FaceObjectList");
                // 从FaceListObject中获取FaceObject
                JSONArray faceObject = faceListObject.getJSONArray("FaceObject");
                // 遍历人脸列表
                for (Object object : faceObject) {
                    JSONObject jsonObject = (JSONObject) object;
                    // 获取人脸
                    ViidFaceRequest viidFaceRequest = JSONObject.parseObject(jsonObject.toJSONString(), ViidFaceRequest.class);
                    // 设置face的id
                    viidFaceRequest.setId(String.valueOf(SnowflakeGenerateIdUtil.getFlowIdInstance().nextId()));
                    // 判断face中的创建时间
                    if (ObjectUtil.isEmpty(viidFaceRequest.getCreateTime())) {
                        viidFaceRequest.setCreateTime(new Timestamp(System.currentTimeMillis()));
                    }
                    // 获取图片信息
                    SubImageInfoObject subImageList = viidFaceRequest.getSubImageList();
                    // 判断人脸对象中的列表是否为空
                    if (ObjectUtil.isNotEmpty(subImageList) && CollUtil.isNotEmpty(subImageList.getSubImageInfoObject())) {
                        // 遍历每个图片对象
                        for (SubImage subImage : subImageList.getSubImageInfoObject()) {
                            // 新建SubImageInfo
                            SubImageInfo subImageInfo = new SubImageInfo();
                            if (!StringUtils.isEmpty(subImage.getData())) {
                                // 大图不存储节省空间
                                String url = "";
                                // 上传minIO
                                if (!subImage.getType().equalsIgnoreCase("14")) {
                                    // base64转换成MultipartFIle
                                    MultipartFile file = ImageUtils.base64ToMultipartFile(subImage.getData());
                                    url = uploadFileMinio(file, subImage.getFileFormat());
                                }
                                // 设置minio的url
                                subImage.setImageUrl(url);
                            }
                            // 设置主键
                            subImage.setId(String.valueOf(SnowflakeGenerateIdUtil.getFlowIdInstance().nextId()));
                            subImage.setViidId(viidFaceRequest.getId());
                            // 设置faceId
                            subImage.setFaceId(viidFaceRequest.getFaceId());
                            // 设置创建时间
                            subImage.setCreateTime(sdf.format(new Date()));
                            // 转换
                            convertFaceImages(subImageInfo, subImage);
                            // 添加到照片列表中
                            insertImageList.add(subImageInfo);
                        }
                    }
                    // 添加到face列表
                    insertFaceList.add(viidFaceRequest);
                }
                // 批量新增人脸及人脸照片列表
                if (CollUtil.isNotEmpty(insertFaceList) && CollUtil.isNotEmpty(insertImageList)) {
                    int insert = viidFaceService.batchInsertFacesAndFacesImages(insertFaceList, insertImageList);
                }
            }
            else if (notificationObj.containsKey("MotorVehicleObjectList")) {
                List<ViidMotorVehicleRequest> insertMotroVehicleList = new ArrayList<>();
                List<SubImageInfo> insertImageList = new ArrayList<>();
                // 从请求的Object中获取MotorVehicleListObject
                JSONObject motorVehicleListObject = (JSONObject) notificationObj.get("MotorVehicleObjectList");
                // 从MotorVehicleListObject中获取MotorVehicleObject
                JSONArray motorVehicleObject = motorVehicleListObject.getJSONArray("MotorVehicleObject");
                String motorVehicleId = null;
                // 遍历机动车列表
                for (Object object : motorVehicleObject) {
                    JSONObject jsonObject = (JSONObject) object;
                    // 获取机动车
                    ViidMotorVehicleRequest viidMotorVehicleRequest = JSONObject.parseObject(jsonObject.toJSONString(), ViidMotorVehicleRequest.class);
                    // 设置机动车的id
                    viidMotorVehicleRequest.setId(String.valueOf(SnowflakeGenerateIdUtil.getFlowIdInstance().nextId()));
                    // 获取机动车的id
                    motorVehicleId = viidMotorVehicleRequest.getMotorVehicleId();
                    // 判断机动车中的创建时间
                    if (ObjectUtil.isEmpty(viidMotorVehicleRequest.getCreateTime())) {
                        viidMotorVehicleRequest.setCreateTime(new Timestamp(System.currentTimeMillis()));
                    }
                    // 获取图片信息
                    SubImageInfoObject subImageList = viidMotorVehicleRequest.getSubImageList();
                    // 判断机动车对象中的列表是否为空
                    if (ObjectUtil.isNotEmpty(subImageList) && CollUtil.isNotEmpty(subImageList.getSubImageInfoObject())) {
                        // 遍历每个图片对象
                        for (SubImage subImage : subImageList.getSubImageInfoObject()) {
                            // 新建SubImageInfo
                            SubImageInfo subImageInfo = new SubImageInfo();
                            if (!StringUtils.isEmpty(subImage.getData())) {
                                // 大图不存储节省空间
                                String url = "";
                                // 上传minIO
                                if (!subImage.getType().equalsIgnoreCase("14")) {
                                    // base64转换成MultipartFIle
                                    MultipartFile file = ImageUtils.base64ToMultipartFile(subImage.getData());
                                    url = uploadFileMinio(file, subImage.getFileFormat());
                                }
                                // 设置minio的url
                                subImage.setImageUrl(url);
                            }

                            // 设置主键
                            subImage.setId(String.valueOf(SnowflakeGenerateIdUtil.getFlowIdInstance().nextId()));
                            subImage.setViidId(viidMotorVehicleRequest.getId());
                            // 设置机动车Id
                            subImage.setMotorVehicleId(viidMotorVehicleRequest.getMotorVehicleId());
                            // 设置创建时间
                            subImage.setCreateTime(sdf.format(new Date()));
                            // 转换
                            convertMotorVehicleImages(subImageInfo, subImage);
                            // 添加到照片列表中
                            insertImageList.add(subImageInfo);
                        }
                    }

                    // 添加到机动车列表
                    insertMotroVehicleList.add(viidMotorVehicleRequest);
                }
                // 批量新增机动车及机动车照片列表
                if (CollUtil.isNotEmpty(insertMotroVehicleList) && CollUtil.isNotEmpty(insertImageList)) {
                    int insert = viidMotorVehicleService.batchInsertMotorVehiclesAndMotorVehiclesImages(insertMotroVehicleList, insertImageList);
                }
            }
        }

        responseStatusListObject.put("ResponseStatusObject", responseStatusObject);
        result.put("ResponseStatusListObject", responseStatusListObject);
        log.info("打印返回的请求参数：{}", result.toJSONString());
        return result.toJSONString();
    }

    private void convertFaceImages(SubImageInfo subImageInfo, SubImage subImage) {
        subImageInfo.setId(subImage.getId());
        subImageInfo.setImageUrl(subImage.getImageUrl());
        subImageInfo.setFaceId(subImage.getFaceId());
        subImageInfo.setEventSort(subImage.getEventSort());
        subImageInfo.setDeviceId(subImage.getDeviceID());
        subImageInfo.setStoragePath(subImage.getStoragePath());
        subImageInfo.setType(subImage.getType());
        subImageInfo.setFileFormat(subImage.getFileFormat());
        subImageInfo.setShotTime(subImage.getShotTime());
        subImageInfo.setWidth(subImage.getWidth());
        subImageInfo.setHeight(subImage.getHeight());
//        subImageInfo.setDataBytes(subImage.getDataBytes());
        subImageInfo.setCreateTime(subImage.getCreateTime());
        subImageInfo.setViidId(subImage.getViidId());
    }

    private void convertMotorVehicleImages(SubImageInfo subImageInfo, SubImage subImage) {
        subImageInfo.setId(subImage.getId());
        subImageInfo.setImageUrl(subImage.getImageUrl());
        subImageInfo.setMotorVehicleId(subImage.getMotorVehicleId());
        subImageInfo.setEventSort(subImage.getEventSort());
        subImageInfo.setDeviceId(subImage.getDeviceID());
        subImageInfo.setStoragePath(subImage.getStoragePath());
        subImageInfo.setType(subImage.getType());
        subImageInfo.setFileFormat(subImage.getFileFormat());
        subImageInfo.setShotTime(subImage.getShotTime());
        subImageInfo.setWidth(subImage.getWidth());
        subImageInfo.setHeight(subImage.getHeight());
//        subImageInfo.setDataBytes(subImage.getDataBytes());
        subImageInfo.setCreateTime(subImage.getCreateTime());
        subImageInfo.setViidId(subImage.getViidId());
    }

    /**
     * minio图片上传
     *
     * @param file file
     * @return 地址
     */
    public String uploadFileMinio(MultipartFile file, String fileFormat) {
        if (file.isEmpty()) {
            throw new RuntimeException("文件不存在！");
        }
        // 判断存储桶是否存在
        if (!minioUtil.bucketExists(minioConfig.getBucketName())) {
            minioUtil.makeBucket(minioConfig.getBucketName());
        }
        if ("Jpeg".equals(fileFormat)) {
            fileFormat = "jpg";
        }
        // 生成文件名
        String fineName = FileUploadUtils.extractFilename(file) + "." + fileFormat;
        try {
            // 上传文件
            Boolean upload = minioUtil.upload(file, fineName, minioConfig.getBucketName());
            // 判断上传是否成功
            if (!upload) {
                return null;
            }
        } catch (Exception e) {
            return null;
        }

        return "/" + minioConfig.getBucketName() + "/" + fineName;
    }
}

